import numpy as np
import matplotlib.pyplot as plt
import matplotlib
print(matplotlib.__version__)

x_data = [1.0,2.0,3.0]
y_data = [2.0,4.0,6.0]

w = 1 # 初始值
a = 0.01 # 学习率

def forward(x):
    return x * w

def cost(xs,ys):
    cost = 0
    for x,y in zip(xs,ys):
        y_pred = forward(x)
        cost = (y_pred - y) **2
    return cost

def gradient(xs,ys):
    grad = 0
    for x,y in zip(xs,ys):
        grad += 2 * x * (x*w-y) # 这里是梯度求完偏导后的公式
    return grad/len(xs)

cost_list = []

print('Before',4,forward(4)) # 未训练前的模型进行预测

for epoch in range(100):
    cost_val = cost(x_data,y_data) # 计算当前w的cost
    cost_list.append(cost_val)
    grad_val = gradient(x_data,y_data) # 计算当前梯度
    w -= a * grad_val # 进行梯度下降
    print('Epoch',epoch,'w=',w,'loss',cost_val)

print('After',4,forward(4)) # 训练后的模型进行预测

# plt.plot(range(0,100), cost_list)
#
# plt.xlabel('epoch')
# plt.ylabel('cost')
# plt.show(block=True)